from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox, QTableWidgetItem
from projectinfo.projinfo import Ui_projinfo_MainWindow
import csv,os,statistics
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
from database import usedb

plt.style.use("seaborn-v0_8-darkgrid")
plt.rcParams['font.sans-serif'] = ['SimHei']  #指定默认字体
plt.rcParams['axes.unicode_minus']=False      #解决保存图像是负号'-'显示为方块的问题
plt.rcParams['figure.constrained_layout.use'] = True
#Constrained layout automatically adjusts subplots so that decorations like tick labels, legends,
# and colorbars do not overlap, while still preserving the logical layout requested by the user.
class projinfo_window(Ui_projinfo_MainWindow):

    def __init__(self):
        # 构造方法
        super(projinfo_window, self).__init__()
        # 只显示关闭按钮
        self.setupUi(self)
        self.setWindowFlags(QtCore.Qt.WindowCloseButtonHint)
        self.setFixedSize(820, 1080)
        self.show_info()
        # 判断是否为管理员
        if usedb.ifadmin!=1:
            self.actionnewpile.setEnabled(False)
            self.actiondeletepile.setEnabled(False)
            self.actioncheckdata.setEnabled(False)
            self.actionoutputtable.setEnabled(False)
            self.actionoutputpic.setEnabled(False)
        self.setStyleSheet(
            """
            QMainWindow {
            background-color: white; / *设置背景色为白色 * /
            }
            
            QLabel {
            background-color: white; / *设置背景色为白色 * /
            }
            
        """
            )
        self.show()
        from DPmain_logic import dp_window
        self.dpwin = dp_window()

        self.dpwin.close()
        self.actionnewpile.triggered.connect(self.dpwin.new_pile)
        self.actionviewpile.triggered.connect(self.dpwin.view_pile)
        self.actiondeletepile.triggered.connect(self.dpwin.delete_pile)
        self.actioncheckdata.triggered.connect(self.dpwin.check_data)
        self.actionoutputtable.triggered.connect(self.dpwin.output_table)
        self.actionoutputpic.triggered.connect(self.dpwin.output_pic)

    def show_info(self):
        # 显示信息
        dir_proj = os.path.join(usedb.cur_path, usedb.cur_proj)
        csv_projinfo = os.path.join(dir_proj, f'{usedb.cur_proj}综合质量评分（表一）.csv')
        self.lab_projinfo1.setText(f'当前项目为{usedb.cur_proj}，项目路径为{dir_proj}')
        if os.path.exists(dir_proj) and usedb.cur_proj!='':
            # 1、 从table projinfo 读取项目信息
            # csv_pile = os.path.join(dir_proj, f'{usedb.cur_proj}试验成果及得分表（表二）.csv')
            # dir_images = os.path.join(dir_proj, '../images')
            # 2、将table中的projinfo信息更新至projinfo窗口
            with open(csv_projinfo, 'r', newline='',encoding='utf-8') as csvfile:
                csvoutput = csv.reader(csvfile)
                projinfohead = next(csvoutput)
                # 设定表格行数和列数
                self.tbw_projinfo.setColumnCount(len(projinfohead))
                self.tbw_projinfo.setHorizontalHeaderLabels(projinfohead)
                # 获取桩号和综合得分
                pilenums = 0
                piles = []
                scores = []
                i = 0
                qualified = 0
                unqualified = 0
                for row in csvoutput:
                    pilenums += 1
                    pile = row[1]
                    piles.append(pile)
                    score = float(row[8])
                    scores.append(score)
                    self.tbw_projinfo.setRowCount(i + 1)
                    if row[9]=='不合格':
                        unqualified += 1
                    else:
                        qualified += 1
                    for j in range(0,len(row)):
                        data = QTableWidgetItem(str(row[j]))
                        data.setTextAlignment(QtCore.Qt.AlignCenter)
                        self.tbw_projinfo.setItem(i, j, data)
                        j += 1
                    i += 1
            if pilenums == 0:
                self.lab_projinfo2.setText(
                    f'项目共有{pilenums}根桩，其中{qualified}根合格，{unqualified}根不合格，合格率为0%')
                self.lab_projinfo3.setText(f'经统计，得分平均值为0，方差0，标准差0')
            else:
                self.lab_projinfo2.setText(
                    f'项目共有{pilenums}根桩，其中{qualified}根合格，{unqualified}根不合格，合格率为{qualified / pilenums:.1%}')
                self.lab_projinfo3.setText(
                    f'经统计，得分平均值为{round(statistics.mean(scores),2)}，方差{round(statistics.pvariance(scores),2)}，标准差{round(statistics.pstdev(scores),2)}')
                self.show_fig(piles, scores, qualified/pilenums)
            self.tbw_projinfo.verticalHeader().setVisible(False)
            self.tbw_projinfo.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
            self.tbw_projinfo.resizeColumnsToContents()
            self.tbw_projinfo.setAlternatingRowColors(True)
            self.tbw_projinfo.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
        else:
            QMessageBox.information(None, '提示', "请先选择项目！", QMessageBox.Ok)

    def show_fig(self, piles, scores, ratio):
        # 生成折线图、直方图、饼图
        # 1、生成折线图
        self.figure1, self.ax1 = plt.subplots()
        self.canvas1 = FigureCanvas(self.figure1)
        # self.figtoolbar = NavigationToolbar(self.canvas, self)
        # self.vlayout1.addWidget(self.figtoolbar)
        self.vlayout1.addWidget(self.canvas1)
        self.ax1.plot(piles, scores,marker='D',ms=5)
        self.ax1.set_xlabel("桩号")
        self.ax1.set_ylabel("得分")
        self.ax1.set_ylim(0, 100)
        self.ax1.set_title("单桩得分折线图")
        self.canvas1.draw()
        # 2、得分频率分布图
        self.figure2, self.ax2 = plt.subplots()
        self.canvas2 = FigureCanvas(self.figure2)
        self.vlayout2.addWidget(self.canvas2)
        bins = [0, 20, 40, 60, 80, 100]
        self.ax2.hist(scores, bins)
        self.ax2.set_xlabel("区间")
        self.ax2.set_ylabel("得分")
        self.ax2.set_title("单桩得分分布图")
        # self.figure2.tight_layout(pad=4)
        self.canvas2.draw()
        # 3、合格率饼图
        self.figure3, self.ax3 = plt.subplots()
        self.canvas3 = FigureCanvas(self.figure3)
        self.vlayout3.addWidget(self.canvas3)
        x = [ratio,1-ratio]
        explode = [0.1, 0]
        labels = [f'合格率{x[0]:.1%}', f'不合格率{x[1]:.1%}']
        self.ax3.set_title("合格率饼图")
        self.ax3.pie(x, explode, labels=labels)
        self.canvas3.draw()